/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.base.util;

import java.util.Collection;
import java.util.Optional;

import org.doll.it.base.enums.CodeEnum;
import org.doll.it.base.exception.BaseException;
import org.springframework.util.Assert;

/**
 * Assertion utility class that assists in validating arguments.
 * 
 * @author Wien(luweien@aliyun.com)
 *
 */
public class AssertUtils extends Assert {

	public static void throwBaseException(boolean expression, BaseException baseException) {
		notNull(baseException, "Throws BaseException instance is null.");
		if (!expression) {
			throw baseException;
		}
	}

	public static void throwBaseException(boolean expression, CodeEnum codeEnum, String extraMsg, Throwable cause) {
		throwBaseException(expression, new BaseException(codeEnum, extraMsg, cause));
	}

	public static void throwBaseException(boolean expression, CodeEnum codeEnum, String extraMsg) {
		throwBaseException(expression, new BaseException(codeEnum, extraMsg));
	}

	public static void throwBaseException(boolean expression, CodeEnum codeEnum) {
		throwBaseException(expression, new BaseException(codeEnum));
	}

	public static void throwBaseException(boolean expression, String message) {
		throwBaseException(expression, new BaseException(message));
	}

	public static void throwBaseException(boolean expression, Throwable cause) {
		throwBaseException(expression, new BaseException(cause));
	}

	public static void throwBaseException(boolean expression, String message, Throwable cause) {
		throwBaseException(true, new BaseException(message, cause));
	}

	/**
	 * 校验ID是否正确，如果不正确，则抛出异常
	 * @param snowflakeId
	 */
	public static void verifyId(Long snowflakeId) {
		throwBaseException(snowflakeId != null && snowflakeId > 0, CodeEnum.ID_FORMAT_ERROR,
				"Id must be greater than 0. current is " + snowflakeId);
	}

	/**
	 * 对象不存在
	 * @param optional 
	 * @param id 
	 */
	public static <T> void exist(Optional<T> optional, Long id) {
		isNull(optional, "Optional must not be null.");
		verifyId(id);
		exist(optional.isPresent(), id);
	}

	/**
	 * 对象存在
	 * @param id
	 */
	public static void exist(boolean expression, Long id) {
		throwBaseException(expression, CodeEnum.OBJECT_NOT_EXIST, "Id is " + id);
	}

	/**
	 * 配置的key存在
	 * @param id
	 */
	public static void existConfig(boolean expression, String key) {
		throwBaseException(expression, CodeEnum.CONFIG_KEY_NOT_EXIST, "Key is " + key);
	}

	/**
	 * 删除正在使用的对象
	 * @param <T>
	 * @param expression
	 * @param id
	 */
	public static <T> void deleteUsingObject(Collection<T> coll, Long id) {
		deleteUsingObject(CollectionUtils.isEmpty(coll), id);
	}

	/**
	 * 删除正在使用的对象
	 * @param expression
	 * @param id
	 */
	public static void deleteUsingObject(boolean expression, Long id) {
		throwBaseException(expression, CodeEnum.CANNOT_DELETE_USING_OBJECT, "Id is " + id);
	}

}
